//
//  WBUserAccount.swift
//  Weibo
//
//  Created by apple on 2016/12/7.
//  Copyright © 2016年 yanjun. All rights reserved.
//

import UIKit

private let accountFile: NSString = "useraccount.json"

// 用户账户信息
class WBUserAccount: NSObject {

    // 访问令牌
    var access_token: String?
    // 用户代号
    var uid: String?
    // access_token的生命周期，单位是秒数。
    var expires_in: TimeInterval = 0 {
        didSet {
            
            expiresDate = Date(timeIntervalSinceNow: expires_in)
            
        }
    }
    
    // 过期日期
    var expiresDate: Date?
    
    
    // 用户昵称
    var screen_name: String?
    // 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    
    
    override var description: String{
        return yy_modelDescription()
    }
    
    override init() {
        super.init()
        
        // 从磁盘加载保存文件 -> 字典
        guard let path = accountFile.cz_appendDocumentDir(),let data = NSData(contentsOfFile: path),let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: Any] else {
         return
        }
        
        // 使用字典设置属性值
        /**** 用户是否登录关键信息 ***/
        yy_modelSet(with: dict ?? [:])
        
        // 判断token时候过期
        if expiresDate?.compare(Date()) != .orderedDescending {
            print("账户过期")
            
            // 清空 token
            access_token = nil
            uid = nil
            
            // 删除账户文件
            try? FileManager.default.removeItem(atPath: path)
        }
        
        print("账户正常\(self)")
        
    }
    
    
    
    func saveAccount() {
        
        var dict = self.yy_modelToJSONObject() as? [String : Any] ?? [:]
        
        // 需要删除expires_in 值
        dict.removeValue(forKey: "expires_in")
        
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),let filePath = accountFile.cz_appendDocumentDir() else {
            return
        }
        
        
        (data as NSData).write(toFile: filePath, atomically: true)
        
        print("用户账户保存成功")
        
    }
    
}
